package com.huzp.net.mysql.jdbc;

import lombok.Data;

import java.nio.ByteBuffer;

/**
 * 握手信息
 */
@Data
public class ShakeInfo {

    /**
     * 协议版本号
     */
    private byte protocol;

    /**
     * 数据库版本
     */
    private String version;

    /**
     * 服务器线程id
     */
    private int thread;

    /**
     * 挑战随机数
     */
    private short random;

    /**
     * 填充值
     */
    private byte fit;

    /**
     * 权能标识 2
     */
    private byte[] flag;

    /**
     * 字符编码
     */
    private byte charset;

    /**
     * 服务器状态 2
     */
    private byte[] status;

    /**
     * 权能标识2  2
     */
    private byte[] flag2;
    /**
     * 挑战长度 1
     */
    private byte length;
    /**
     * 填充值2  10
     */
    private byte[] fit2;
    /**
     * 随机数据2
     */
    private byte[] random2;
    /**
     * 结束
     */
    private byte end;

    public ShakeInfo(ByteBuffer data) {
        data.flip();
        this.protocol = data.get();
        int index = 0;
        byte[] array = data.array();
        int len = array.length;
        for (int i = 1; i < len; i++) {
            if (array[i] == 0x00) {
                index = i;
                break;
            }
        }
        byte[] ver = new byte[index];
        data.get(ver, 0, ver.length);
        this.version = new String(ver);
        this.thread = data.getInt();
        this.random = data.getShort();
        this.fit = data.get();
        this.flag = new byte[]{data.get(), data.get()};
        this.charset = data.get();
        this.status = new byte[]{data.get(), data.get()};
        this.flag2 = new byte[]{data.get(), data.get()};
        this.length = data.get();
        ver = new byte[10];
        data.get(ver, 0, ver.length);
        this.fit2 = ver;
        int rl = len - 1 - data.position();
        ver = new byte[rl];
        data.get(ver, 0, ver.length);
        this.random2 = ver;
        this.end = data.get();
    }
}
